package com.ceres.system.service.impl;

import com.ceres.system.dao.AdminMapper;
import com.ceres.system.dao.UserMapper;
import com.ceres.system.pojo.Admin;
import com.ceres.system.pojo.User;
import com.ceres.system.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 工具方法，根据传入的用户id和角色id数组添加关联表
     *
     * @param roleIds
     * @param userId
     */
    public void addUserAndRole(Integer[] roleIds, Integer userId) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                userMapper.addUserAndRole(roleId, userId);
            }
        }

    }


    /**
     * 添加平台用户
     *
     * @param roleIds
     * @param user
     * @param username
     */
    @Override
    public void addUser(Integer[] roleIds, User user, String username) {
        if (usernameExistChecking(user)) {
            User userByLoginName = userMapper.findUserByUserName(username);
            //通过登录名查询到农业组织超级管理员的id
            Integer id = userByLoginName.getId();
            Integer customerId = userByLoginName.getCustomerId();
            //将农业组织的超级管理员id设置到用户的pid
            user.setPid(id);
            user.setCustomerId(customerId);
            user.setStatus("1");
            //进行密码加密加盐处理,默认是没有处理的
            String gensalt = BCrypt.gensalt();
            user.setPassword("123456");
            String saltPassword = BCrypt.hashpw(user.getPassword(), gensalt);
            user.setPassword(saltPassword);
            userMapper.insertSelective(user);
            Integer userId = user.getId();
            this.addUserAndRole(roleIds, userId);
        } else {
            throw new RuntimeException("用户名已存在");
        }
    }

    @Override
    public List<User> findAll() {
        List<User> userList = userMapper.selectAll();
        return userList;
    }

    /**
     * 删除方法，将用户状态改为已删除
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //通过用户id获取admin对象
        User user = userMapper.selectByPrimaryKey(id);
        //将用户状态改为已删除
        user.setStatus("2");
        //将修改后的用户状态信息更新
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setPassword(null);
        return user;
    }

    /**
     * 根据用户id查询关联角色
     *
     * @param id
     * @return
     */
    @Override
    public Integer[] findRoleByUser(Integer id) {
        Integer[] roleByAdmin = userMapper.findRoleByUser(id);
        return roleByAdmin;
    }

    /**
     * 修改用户信息，并重新关联角色
     *
     * @param roleIds
     * @param user
     */
    @Override
    public void updateUser(Integer[] roleIds, User user) {
        //根据用户修改后的信息，查询出数据库中的用户信息
        User user1 = userMapper.selectOne(user);
        if (user != null) {
            //将用户修改的字段更新到数据库中，id，username，status三个字段不可更改。
            user1.setName(user.getName());
            user1.setPassword(user.getPassword());
            userMapper.updateByPrimaryKeySelective(user1);
            //根据用户id删除关联的角色
            userMapper.deleteRolesByUserId(user.getId());
            //根据用户id将新的角色信息添加到中间表中
            addUserAndRole(roleIds, user1.getId());
        } else {
            throw new RuntimeException("用户不存在");
        }

    }

    /**
     * 重置用户密码
     *
     * @param id
     */
    @Override
    public void resetPassword(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (!"2".equals(user.getStatus())) {
            String gensalt = BCrypt.gensalt();
            user.setPassword("123456");
            String saltPassword = BCrypt.hashpw(user.getPassword(), gensalt);
            user.setPassword(saltPassword);
            user.setStatus("1");
            userMapper.updateByPrimaryKeySelective(user);
        } else {
            throw new RuntimeException("用户状态错误");
        }
    }

    /**
     * 多条件查询并分页
     *
     * @param queryCondition 查询条件
     * @param page           当前页码
     * @param size           每页显示条数
     * @param username
     * @return
     */
    @Override
    public Page<User> queryUser(Map<String, Object> queryCondition, int page, int size, String username) {

        User userByLoginName = userMapper.findUserByUserName(username);
        PageHelper.startPage(page, size);
        Integer customerId = userByLoginName.getCustomerId();
        Example example = createExample(queryCondition, customerId);
//        criteria.andEqualTo("customerId", customerId);
        Page<User> userPage = (Page<User>) userMapper.selectByExample(example);
//        Page<User> pageResult = userMapper.findByCondition(queryCondition, customerId);
        return userPage;



        /*PageHelper.startPage(page, size);
        User userByLoginName = userMapper.findUserByUserName(username);
        Integer customerId = userByLoginName.getCustomerId();
        List<User> userPage = userMapper.findByCondition(queryCondition, customerId);
        Page<User> userPageInfo = (Page<User>)userPage;
        long total = userPageInfo.getTotal();*/
//        return userPageInfo;
    }

    /**
     * 多条件查询并分页
     * @param queryCondition 查询条件
     * @param page 当前页码
     * @param size 每页显示条数
     * @return
     */
    @Override
    public Page<Admin> queryAdmin(Map<String, Object> queryCondition, int page, int size,String username) {
        PageHelper.startPage(page,size);
        Example example = new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if (queryCondition!=null){
            //用户真实姓名
            if (queryCondition.get("name")!=null&&!"".equals(queryCondition.get("name"))){
                criteria.andLike("name","%"+queryCondition.get("name")+"%");
            }
            //用户登录名
            if (queryCondition.get("username")!=null&&!"".equals(queryCondition.get("username"))){
                criteria.andLike("username","%"+queryCondition.get("username")+"%");
            }
            //用户手机号
            if (queryCondition.get("phone")!=null&&!"".equals(queryCondition.get("phone"))){
                criteria.andLike("phone","%"+queryCondition.get("phone")+"%");
            }
        }

        return (Page<Admin>) adminMapper.selectByExample(example);
    }

    /**
     * 查询用户名是否存在
     *
     * @param user
     * @return
     */
    Boolean usernameExistChecking(User user) {
        String username = user.getUsername();
        User user1 = userMapper.findUserByUserName(username);
/*        if (admin1==null){
            return true;
        }else {
            return false;
        }*/
        return user1 == null ? true : false;
    }

    /**
     * 修改密码
     *
     * @param password
     * @param username
     */
    @Override
    public void changPassword(String password, String username) {
        User userByUsername = userMapper.findUserByUserName(username);
        //进行密码加密加盐处理,默认是没有处理的
        String gensalt = BCrypt.gensalt();
        userByUsername.setPassword(password);
        String saltPassword = BCrypt.hashpw(userByUsername.getPassword(), gensalt);
        userByUsername.setPassword(saltPassword);
        userMapper.updateByPrimaryKeySelective(userByUsername);
    }

    private Example createExample(Map<String, Object> queryCondition,Integer customerId){
        Example example=new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (queryCondition!=null){
            criteria.andEqualTo("customer_id",customerId);
            //用户真实姓名
            if (queryCondition.get("name") != null && !"".equals(queryCondition.get("name"))) {
                criteria.andLike("name", "%" + queryCondition.get("name") + "%");
            }
            //用户登录名
            if (queryCondition.get("username") != null && !"".equals(queryCondition.get("username"))) {
                criteria.andLike("username", "%" + queryCondition.get("username") + "%");
            }
        }
        return example;
    }

}
